<template>
  <!-- 计划外报工单表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="50%"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
      >
        <h4 class="mb-[20px] mt-[20px]" v-if="props.isReadonly">基本信息</h4>
        <el-row v-if="props.isReadonly">
          <el-col :span="6">
            <el-form-item label="计划外报工单编号" prop="unscheduledReportCode">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.unscheduledReportCode"
                placeholder="请输入计划外报工单编号"
                clearable
              />
              <span class="word" v-else>
                {{ formData.unscheduledReportCode }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工厂编号" prop="plantCode">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.plantCode"
                placeholder="请输入工厂编号"
                clearable
              />
              <span class="word" v-else>
                {{ formData.plantCode }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工作中心名称" prop="workCenterName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.workCenterName"
                placeholder="请输入工作中心名称"
                clearable
              />
              <span class="word" v-else>
                {{ formData.workCenterName }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="班组名称" prop="crewName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.crewName"
                placeholder="请输入班组名称"
                clearable
              />
              <span class="word" v-else>
                {{ formData.crewName }}
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="props.isReadonly">
          <el-col :span="6">
            <el-form-item label="班次名称" prop="shiftName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.shiftName"
                placeholder="请输入班次名称"
                clearable
              />
              <span class="word" v-else>
                {{ formData.shiftName }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报工状态" prop="reportState">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.reportState"
                clearable
                placeholder="请选择报工状态"
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('ReportState')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span v-else>{{
                dictionaryStore.filterDictName(
                  "ReportState",
                  formData.reportState
                )
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.memberName"
                clearable
                placeholder="请选择报工状态"
              />
              <span v-else>{{ formData.memberName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <h4 class="mb-[20px] mt-[20px]" v-if="props.isReadonly">详细数据</h4>
        <el-card shadow="never" class="table-container" v-if="props.isReadonly">
          <!-- <template #header>
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增</el-button
            >
          </template> -->
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column
                label="计划外报工类型"
                props="unscheduledReportType"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.unscheduledReportType'"
                    :rules="rules.sonunscheduledReportType"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.unscheduledReportType"
                      clearable
                      placeholder="请选择计划外报工类型"
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList(
                          'ReportType'
                        )"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <span v-else>{{
                      dictionaryStore.filterDictName(
                        "ReportType",
                        row.unscheduledReportType
                      )
                    }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="计划外报工说明"
                props="unscheduledReportContent"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.unscheduledReportContent'"
                    :rules="rules.sonunscheduledReportContent"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.unscheduledReportContent"
                      placeholder="请输入计划外报工说明"
                      clearable
                    />
                    <span v-else>{{ row.unscheduledReportContent }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="开始时间"
                props="startTime"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.startTime'"
                    :rules="rules.sonstartTime"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.startTime"
                      placeholder="请输入开始时间"
                      clearable
                    />
                    <span v-else>{{ row.startTime }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="完工时间"
                props="completeTime"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.completeTime'"
                    :rules="rules.soncompleteTime"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.completeTime"
                      placeholder="请输入完工时间"
                      clearable
                    />
                    <span v-else>{{ row.completeTime }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="中断时长/分"
                props="totalTime"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.totalTime'"
                    :rules="rules.sontotalTime"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.totalTime"
                      placeholder="请输入中断时长/分"
                      clearable
                    />
                    <span v-else>{{ row.totalTime }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="300"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
        <h4 class="mb-[20px] mt-[20px]" v-if="props.isReadonly">审批数据</h4>

        <el-card shadow="never" class="table-container" v-if="props.isReadonly">
          <!-- <template #header>
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增</el-button
            >
          </template> -->
          <div class="formTable">
            <el-table
              :data="formData.detailsApproval"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column
                label="审批状态"
                props="approvedByState"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.approvedByState'"
                    :rules="rules.approvedByState"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.approvedByState"
                      clearable
                      placeholder="审批状态"
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList(
                          'ReportState'
                        )"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <span v-else>{{
                      dictionaryStore.filterDictName(
                        "ReportState",
                        row.approvedByState
                      )
                    }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="审批人"
                props="approvedByName"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.approvedByName'"
                    :rules="rules.approvedByName"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.approvedByName"
                      placeholder="请输入审批人"
                      clearable
                    />
                    <span v-else>{{ row.approvedByName }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="审批时间"
                props="approvalTime"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.approvalTime'"
                    :rules="rules.approvalTime"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.approvalTime"
                      placeholder="请输入审批时间"
                      clearable
                    />
                    <span v-else>{{ row.approvalTime }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="审批意见"
                props="approvalOpinions"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.approvalOpinions'"
                    :rules="rules.approvalOpinions"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.approvalOpinions"
                      placeholder="请输入审批意见"
                      clearable
                    />
                    <span v-else>{{ row.approvalOpinions }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="300"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESUNSCHEDULEDREPORTADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  unscheduledReportCode: "",
  unscheduledReportType: "",
  unscheduledReportContent: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  producePlanId: "",
  producePlanCode: "",
  produceOrderId: "",
  produceOrderCode: "",
  workCenterId: "",
  workCenterCode: "",
  workCenterName: "",
  crewId: "",
  crewName: "",
  shiftId: "",
  shiftName: "",
  startTime: "",
  completeTime: "",
  totalTime: "",
  totalCost: "",
  reportQuantity: "",
  reportState: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  memberName: "",
  details: [
    {
      id: "",
      unscheduledReportId: "",
      unscheduledReportCode: "",
      unscheduledReportType: "",
      unscheduledReportContent: "",
      startTime: "",
      completeTime: "",
      totalTime: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
  detailsApproval: [],
  detailsMember: [],
});

/** rules规则 */
const rules = reactive({
  unscheduledReportCode: [
    { required: true, message: "请输入计划外报工单编号", trigger: "blur" },
  ],
  plantCode: [{ required: true, message: "请输入工厂编号", trigger: "blur" }],
  workCenterName: [
    { required: true, message: "请输入工作中心名称", trigger: "blur" },
  ],
  crewName: [{ required: true, message: "请输入班组名称", trigger: "blur" }],
  shiftName: [{ required: true, message: "请输入班次名称", trigger: "blur" }],
  reportState: [{ required: true, message: "请输入报工状态", trigger: "blur" }],
  lastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { required: true, message: "请输入更新人名", trigger: "blur" },
  ],
  enabled: [{ required: true, message: "请输入是否启用", trigger: "blur" }],
  deleted: [{ required: true, message: "请输入删除标识", trigger: "blur" }],
  sonunscheduledReportType: [
    { required: true, message: "请输入计划外报工类型", trigger: "blur" },
  ],
  sonunscheduledReportContent: [
    { required: true, message: "请输入计划外报工说明", trigger: "blur" },
  ],
  sonstartTime: [
    { required: true, message: "请输入开始时间", trigger: "blur" },
  ],
  soncompleteTime: [
    { required: true, message: "请输入完工时间", trigger: "blur" },
  ],
  sontotalTime: [{ required: true, message: "请输入总工时", trigger: "blur" }],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details = {
  id: "",
  unscheduledReportId: "",
  unscheduledReportCode: "",
  unscheduledReportType: "",
  unscheduledReportContent: "",
  startTime: "",
  completeTime: "",
  totalTime: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
        getdetailsApproval();
        getdetailsMember();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [details];
  formData.id = "";
  formData.unscheduledReportCode = "";
  formData.unscheduledReportType = "";
  formData.unscheduledReportContent = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.producePlanId = "";
  formData.producePlanCode = "";
  formData.produceOrderId = "";
  formData.produceOrderCode = "";
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.workCenterName = "";
  formData.crewId = "";
  formData.crewName = "";
  formData.shiftId = "";
  formData.shiftName = "";
  formData.startTime = "";
  formData.completeTime = "";
  formData.totalTime = "";
  formData.totalCost = "";
  formData.reportQuantity = "";
  formData.reportState = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 计划外报工单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/mesunscheduledreport/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/mes/mesunscheduledreport/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
async function getdetailsApproval() {
  let sondetails = await request({
    url: "/mes/mesunscheduledreport/getDetailsApproval",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.detailsApproval = sondetails.data;
}

/**
 * 获取申请人信息
 */
async function getdetailsMember() {
  let sondetails = await request({
    url: "/mes/mesunscheduledreport/getDetailsMember",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.memberName = sondetails.data
    .map((item) => item.memberName)
    .toString();
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
